<template>
  <view class="table-page-container">
    <!-- 筛选栏 -->
    <view class="header" v-if="showHeader">
      <sv-table-header @submit="submitFilter"></sv-table-header>
    </view>
    <!-- 表格头部控制栏 -->
    <view class="control">
      <el-button type="primary" plain size="small" :icon="Plus" @click="add">新增</el-button>
      <el-button type="danger" plain size="small" :icon="Delete" @click="selectionRemove">
        批量删除
      </el-button>
      <view style="flex: 1"></view>
      <sv-excel-menu
        type="exam"
        :menu="exportConfig"
        :exportParams="dataParams"
        @noCoverImport="importOver"
        @coverImport="importOver"
      ></sv-excel-menu>
      <el-button
        type="primary"
        link
        :icon="showHeader ? View : Hide"
        @click="showHeader = !showHeader"
      ></el-button>
      <el-button type="primary" link :icon="RefreshRight" @click="refresh"></el-button>
    </view>

    <view class="main-box">
      <!-- 侧边栏 -->
      <view class="left-side">
        <el-tree
          class="sv-el-tree"
          style="width: 120px"
          :data="sideTreeData"
          :props="{
            children: 'children',
            label: 'value'
          }"
          highlight-current
          @current-change="treeNodeChange"
        />
      </view>

      <!-- 表格主体 -->
      <view class="right-table">
        <el-table
          class="sv-el-table"
          v-loading="loading"
          :data="tableData"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center" width="50" fixed="left" />
          <el-table-column
            prop="exam_index"
            label="序号"
            align="center"
            width="60"
          ></el-table-column>
          <el-table-column
            prop="exam_id"
            label="试题ID"
            width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="exam_title"
            label="试题标题"
            width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column prop="exam_type" label="试题类型" align="center" width="120">
            <template #default="scope">
              {{ examConfig.paperTypeDict[scope.row.exam_type] }}
            </template>
          </el-table-column>
          <el-table-column prop="from_lib" label="所属题库" width="160">
            <template #default="scope">
              {{
                sideTreeData.find((item) => item.key == scope.row.from_lib)?.value ||
                scope.row.from_lib
              }}
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单元章节" width="160">
            <template #default="scope">
              {{
                sideTreeData
                  .find((item) => item.key == scope.row.from_lib)
                  ?.children.find((it) => it.key == scope.row.unit)?.value || scope.row.unit
              }}
            </template>
          </el-table-column>
          <el-table-column prop="exam_name" label="试题题干" :min-width="300" show-overflow-tooltip>
            <template #default="scope">
              <text v-html="scope.row.exam_name"></text>
            </template>
          </el-table-column>
          <el-table-column prop="exam_option" label="试题选项" :min-width="300">
            <template #default="scope">
              <view v-for="item in scope.row.exam_option" :key="item.key" class="flex">
                <text>{{ item.key }}.&nbsp;</text>
                <text v-html="item.value"></text>
              </view>
            </template>
          </el-table-column>
          <el-table-column prop="exam_answer" label="试题答案" :min-width="160"></el-table-column>
          <el-table-column prop="analysis" label="答案解析" :min-width="300">
            <template #default="scope">
              <text v-html="scope.row.analysis"></text>
            </template>
          </el-table-column>
          <el-table-column
            prop="comment"
            label="备注"
            width="300"
            show-overflow-tooltip
          ></el-table-column>

          <el-table-column label="配置" align="center" :width="160" fixed="right">
            <template #default="scope">
              <el-button-group>
                <el-button text size="small" :icon="EditPen" @click="edit(scope.row)">
                  编辑
                </el-button>
                <el-button text size="small" :icon="Delete" @click="del(scope.row)">删除</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <view class="sv-pagination">
          <view class="flex-vhc text-cyan text-sm">初始默认全库查询</view>
          <view class="flex-sub"></view>
          <sv-pagination
            :pagingParams="dataParams"
            :total="total"
            @update:page-size="handleSizeChange"
            @update:current-page="handleCurrentChange"
          />
        </view>
      </view>
    </view>
    <!-- 表单抽屉弹窗 -->
    <sv-form
      v-model="showForm"
      :form-init="formInit"
      :form-mode="formMode"
      @submit="submitForm"
    ></sv-form>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import SvForm from './components/sv-form/sv-form.vue'
import SvTableHeader from './components/sv-table-header/sv-table-header.vue'
import { RefreshRight, Plus, EditPen, Delete, View, Hide } from '@element-plus/icons-vue'
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
import { examList, examAdd, examDelete, examUpdate } from '@/service/api/exam'
import { useSysStore } from '@/store/sys'
import { isEmpty } from 'lodash-es'
import { libList } from '@/service/api/lib'
import examConfig from '@/uni_modules/sv-exam-plus/config.js'

const showHeader = ref(useSysStore().platform == 'pc') // 头部筛选栏显示
const tableData = ref([]) // 菜单表格
const loading = ref(false) // 表格loading
const dataParams = ref({ pagesize: 10, pagenum: 1 }) // 筛选参数
const total = ref(0) // 表格总数
const showForm = ref(false) // 显示表单
const formInit = ref({}) // 表单初始值
const formMode = ref('') // 表单模式 add / edit

// 初始获取表格数据
handleTable(dataParams.value)

async function handleTable(params) {
  loading.value = true

  const dataRes = await examList(params)
  tableData.value = dataRes.data || []
  total.value = dataRes.total || 0

  if (!dataRes.success) {
    ElMessage({
      message: dataRes?.message || dataRes?.error?.message,
      type: 'warning'
    })
  }

  loading.value = false
}

// 刷新
function refresh() {
  tableData.value = [] // 置空数据
  handleTable(dataParams.value)
}

// 新增
function add() {
  // 若题库和单元未选择，则不允许新增
  if (!dataParams.value.from_lib || !dataParams.value.unit) {
    ElMessage({
      message: '请先选择题库和单元章节',
      type: 'warning'
    })
    return
  }

  formInit.value = {} // 置空参数
  // 初始化参数
  formInit.value.from_lib = dataParams.value.from_lib
  formInit.value.unit = dataParams.value.unit

  formMode.value = 'add'
  showForm.value = true
}

// 编辑
function edit(item) {
  formInit.value = item // 携带参数
  formMode.value = 'edit'
  showForm.value = true
}

// 提交表单
async function submitForm(e) {
  let result = {}
  switch (e.mode) {
    case 'add':
      // 新增添加
      result = await examAdd(e.data)
      break
    case 'edit':
      // 编辑更新
      result = await examUpdate(e.data)
      break
  }

  if (result.success) {
    ElNotification({
      title: 'Success',
      message: result?.message,
      type: 'success'
    })

    refresh()
  } else {
    ElNotification({
      title: 'Error',
      message: result?.message || result?.error?.message,
      type: 'error'
    })
  }
}

// 删除
function del(item) {
  const { exam_id } = item
  ElMessageBox.confirm(`确认删除${exam_id}吗？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 确认删除操作
      const deleteRes = await examDelete({ exam_id })
      ElMessage({
        type: 'success',
        message: deleteRes?.message || deleteRes?.error?.message
      })

      refresh()
    })
    .catch(() => {})
}

// 多选
const batchSelection = ref([])
function handleSelectionChange(e) {
  batchSelection.value = e.map((item) => item.exam_id)
}

// 批量删除
function selectionRemove() {
  if (isEmpty(batchSelection.value)) return

  ElMessageBox.confirm(`确认批量删除所选项吗？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 确认批量删除操作
      const deleteRes = await examDelete({
        exam_id: batchSelection.value
      })

      ElMessage({
        type: 'success',
        message: deleteRes?.message || deleteRes?.error?.message
      })

      refresh()
    })
    .catch(() => {})
}

/**
 * Excel导入导出
 */
const exportConfig = ref(['downloadTemplate', 'noCoverImport', 'coverImport'])

function importOver(res) {
  ElMessage({
    type: res.code == 200 ? 'success' : 'warning',
    message: res.message
  })
  refresh()
}

// 头部筛选栏筛选条件
async function submitFilter(e) {
  Object.assign(dataParams.value, e)
  handleTable(dataParams.value)
}

// 分页
function handleSizeChange(e) {
  dataParams.value.pagesize = e
  handleTable(dataParams.value)
}
function handleCurrentChange(e) {
  dataParams.value.pagenum = e
  handleTable(dataParams.value)
}

// 左侧树
const sideTreeData = ref([])

async function handleSideTree() {
  const libRes = await libList()
  sideTreeData.value = transformTree(libRes.data)
}
handleSideTree()

function transformTree(originalArray) {
  return originalArray.map((item) => {
    // 在子节点中添加id为父节点lib_id
    item.lib_chapter.forEach((it) => {
      it.from_lib = item.lib_id
    })
    return {
      key: item.lib_id,
      value: item.lib_name,
      children: item.lib_chapter
    }
  })
}

async function treeNodeChange(e) {
  if (isEmpty(e.children)) {
    // 点击树节点后执行的操作
    dataParams.value.from_lib = e.from_lib
    dataParams.value.unit = e.key

    await handleTable(dataParams.value)

    if (!isEmpty(tableData.value)) {
      // 有数据时才能导出
      exportConfig.value = [
        'downloadTemplate',
        'noCoverImport',
        'coverImport',
        'curPageExport',
        'allPageExport'
      ]
    } else {
      exportConfig.value = ['downloadTemplate', 'noCoverImport', 'coverImport']
    }
  }
}
</script>

<style lang="scss">
.main-box {
  display: flex;
  flex-grow: 1;
  flex-shrink: 0;
  height: 0;

  .left-side {
    margin-right: 10px;
  }

  .right-table {
    flex: 1;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: auto;
  }
}
</style>
